var layer = layui.layer, //弹层
    table = layui.table, //表格
    form = layui.form,
    $ = layui.jquery,
    changeList=[],
    laydate = layui.laydate,
    indexs = 0,
    checkboxs =false,
    sourceType=getQueryVariable("sourceType")
;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        getxmselect("#operationCode","operationCode", userTree);
        getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        getxmselect("#salesmanCode","salesmanCode", []);
    }
})()


layer.ready(function () {
    $.ajax({
        url: 'billChange/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#companyCode").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
            }

            form.render();
        }
    });

});

//报关明细集合
let getBillDeclareInfoList=[];
table.render({
    elem: '#mains'
    ,data:getBillDeclareInfoList
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'},
        {field:'billNo', title:'发票编号',sort:true,width: 220},
        {field: 'signingCompanyName', width: 120, title: '签约公司',sort:true},
        {field: 'signingCompanyCode', hide:true,title: '签约公司编码'},
        {field: 'supplierName', width: 120, title: '供应商',sort:true},
        {field: 'supplierCode', hide:true,title: '供应商编码'},
        {field: 'time', title:'出运日期',sort:true,width: 120},
        {field: 'productType', title:'产品类型',sort:true,width: 120,templet: function(data) {
                if (data.productType=="1"){
                    return "成品";
                }else{
                    return "配件";
                }
            }
        },
        {field: 'saleContractNo', width: 120, title: '销售合同号',sort:true},
        {field: 'purchaseNo', width: 120, title: '采购单号',sort:true},
        {field: 'productCode', width: 120, title: '产品编码',sort:true},
        {field: 'specNo', width: 120, title: '规格编码',sort:true},
        {field: 'productSpecExplanation', width: 120, title: '规格说明',sort:true},
        {field: 'productCname', width: 120, title: '中文名称',sort:true},
        {field: 'productEname', width: 120, title: '英文名称',sort:true},
        {field: 'productCdesc', width: 120, title: '中文描述',sort:true},
        {field: 'productEdesc', width: 120, title: '英文描述',sort:true},
        {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
        {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
        {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
        {field: 'canBillingAmount', width: 120, title: '可开票数量',sort:true},
        {field: 'productNum', width: 120, title: '产品数量',sort:true},
        {field: 'productUnitName', width: 120, title: '单位名称',sort:true},
        {field: 'productUnitCode',hide:true, title: '单位编码',sort:true},
        {field: 'costUnitPrice', width: 120, title: '成本单价',sort:true},
        {field: 'color', width: 120, title: '颜色'},
        {field: 'grossWeight', width: 120, title: '毛重', sort:true},
        {field: 'grossWeightSubtotal', width: 120, title: '毛重小计', sort:true},
        {field: 'netWeight', width: 120, title: '净重', sort:true},
        {field: 'netWeightSubtotal', width: 120, title: '净重小计', sort:true},
        {field: 'bulk', width: 120, title: '体积', sort:true},
        {field: 'price', width: 120, title: '外币单价', sort:true},
        {field: 'clientContractNo', width: 120, title: '客户合同号',sort:true},
        {field: 'operationName', width: 120, title: '操作员',sort:true},
        {field: 'salesmanName', width: 120, title: '业务员',sort:true},

    ]]
    ,id: 'mainstableid'
    ,height: 830
    ,page: true
    ,limit: 20
    ,limits: [20, 50, 100]
});
//提交查询条件
form.on('submit(submitform)', function(data){
    data.field.statusList="3,4"
    if (data.field.operationCode==null || data.field.operationCode===""){
        data.field.operationCode=user.code;
    }
    data.field.sourceType=sourceType;
    table.reload('mainstableid', {
        page: {
            limit:20,
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
        ,url:'billing/getCarryDetailProductListByPage'
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    let mainData =   table.checkStatus("mainstableid").data;
    if(mainData.length == 0){
        layer.msg("请选择数据")
    }else{
        let oldData =  parent.table.cache["moaidetailtableid"];
        let newArr=[];
        for (let i = 0; i < mainData.length; i++) {
            let newTemp = {};
            newTemp.tempId=Number(Math.random().toString().substr(3,3) + Date.now()).toString(36);
            //填充到开票主表
            newTemp.billNo=mainData[i].billNo;
            newTemp.carryDetail="carryDetail";
            newTemp.companyName=mainData[i].signingCompanyName;
            newTemp.companyCode=mainData[i].signingCompanyCode;
            newTemp.supplyCode=mainData[i].supplierCode;
            newTemp.supplyName=mainData[i].supplierName;
            //填充到开票明细
            newTemp.saleContractCode=mainData[i].saleContractNo;
            newTemp.stockCode=mainData[i].purchaseNo;
            newTemp.goodsCode= mainData[i].productCode;
            newTemp.specCode= mainData[i].specNo;
            newTemp.goodsSpec= mainData[i].productSpecExplanation;
            newTemp.goodsCname= mainData[i].productCname;
            newTemp.goodsEname= mainData[i].productEname;
            newTemp.goodsCdesc= mainData[i].productCdesc;
            newTemp.goodsEdesc= mainData[i].productEdesc;
            newTemp.goodsNum= mainData[i].canBillingAmount;
            newTemp.goodsUnit= mainData[i].productUnitName;
            newTemp.invoiceUnitPrice= mainData[i].costUnitPrice;//开票单价是成本单价
            newTemp.invoiceSubtotal= 0;//开票小计
            newTemp.colour= mainData[i].color;
            newTemp.goodsGross= mainData[i].grossWeight;
            newTemp.totalGross= mainData[i].grossWeightSubtotal;
            newTemp.netWeight= mainData[i].netWeight;
            newTemp.totalNet= mainData[i].netWeightSubtotal;
            newTemp.bulk= mainData[i].bulk;
            newTemp.purchaseUnitPrice= 0;//采购单价
            newTemp.unitCost= mainData[i].costUnitPrice;//成本单价
            newTemp.costSubtotal= 0;//成本小计
            newTemp.clientContractNo=mainData[i].clientContractNo;
            newTemp.declarePrice= 0;
            newTemp.totalPrice= 0;
            newTemp.productType= parseInt(mainData[i].productType);
            newTemp.customerInvoiceGoodsName=mainData[i].customerInvoiceGoodsName;
            newTemp.customerInvoiceSpecModel=mainData[i].customerInvoiceSpecModel;
            newTemp.customerMaterialsCode=mainData[i].customerMaterialsCode;

            newTemp.invoiceType= 5;//开票单据来源（1导入报关，2导入采购，3导入外销，4导入结汇，5导入出运明细）
            newArr.push(newTemp);
        }

        oldData.push.apply(oldData,newArr);


        parent.table.reload('moaidetailtableid',{data : oldData}); //刷新主信息表格
        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
    }
})



$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})
